package com.example.tetris;

import com.example.tetris.Tetris.Tetris;
import com.example.tetris.beans.MyCommondialog;
import com.example.tetris.beans.MyToastdialog;
import com.example.tetris.listeners.TetrisGameoverListener;
import com.example.tetris.listeners.TetrisNextBlockListener;
import com.example.tetris.listeners.TetrisRowRemovedListener;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.data.rdb.ValuesBucket;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.net.Uri;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class MainAbility extends Ability {
    private Tetris tetris;
    private DirectionalLayout layoutTetris;
    protected int seconds = 0;
    //判断游戏是否开始，防止游戏开始后还可以点击start按钮
    protected boolean isStart = false;
    //判断游戏是否结束，防止游戏还未结束直接重新开始
    protected boolean isOver = false;
    //判断游戏模式
    String game_mode;

    //记录游戏时长的TickTimer
    protected TickTimer timer_seconds;
    //    protected Timer timer_seconds;
    //记录分数
    final int[] currentScore = new int[1];
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private Uri uri = Uri.parse("dataability:///com.example.tetris.SQLite");
    private Uri uri_df = Uri.parse("dataability:///com.example.tetris.SQLite_df");
    DataAbilityHelper helper = DataAbilityHelper.creator(this);


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        game_mode= intent.getStringParam("mode_flag");
        Text text=(Text)findComponentById(ResourceTable.Id_main_mode);
        if(Objects.equals(game_mode, "classic"))
            text.setText("经典 四格骨牌");
        else if(Objects.equals(game_mode, "difficulty"))
            text.setText("困难 五格骨牌");
        else if(Objects.equals(game_mode, "endgm"))
            text.setText("残局 四格骨牌");
        //此处layoutTetris为左侧游戏界面
        layoutTetris =
                (DirectionalLayout) findComponentById(ResourceTable.Id_layout_tetris);
        if (layoutTetris != null) {

            //创建Tetris对象，并与layoutTetris对象绑定，第二种重载方式，drawblock为空
            tetris = new Tetris(this, layoutTetris);
            tetris.mode_flag = game_mode;
            Button buttonStart = (Button) findComponentById(ResourceTable.Id_start);

            if (buttonStart != null) {

                buttonStart.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {

                        if (!isStart) {
                            if (!tetris.isPlaying) {
                                MyToastdialog.showTip(getContext(), "游戏开始");
                                //游戏开始时，按钮中文字变色
                                buttonStart.setTextColor(Color.WHITE);

                                isStart = true;
                                //显示用时的文本
                                Text seconds_text = (Text) findComponentById(ResourceTable.Id_seconds);
                                //记录游戏时长的定时器
                                timer_seconds = (TickTimer) findComponentById(ResourceTable.Id_seconds);
                                //表示正向计时
                                timer_seconds.setCountDown(false);
                                //表示计时格式
                                timer_seconds.setFormat("mm:ss");
                                timer_seconds.start();
                                tetris.start();
                            }
                        } else if (isStart && !isOver) {
                            MyToastdialog.showTip(getContext(), "游戏正在进行，请勿重复操作");
                        } else if (isStart && isOver) {
                            MyToastdialog.showTip(getContext(), "游戏已结束，请点击重新开始");
                        }
                    }
                });

            }


            //为Tetris组件指定监听下一个方块的监听器
            tetris.setOnTetrisNextBlock(new TetrisNextBlockListener() {
                @Override
                //每产生下一个方块，就会调用一次该方法
                public void onNextBlock(int[][] block) {
                    //更新UI使用
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            //下一个方块就绘制在这个布局上,layoutNext绑定layoutnext对象
                            DirectionalLayout layoutNext = (DirectionalLayout) findComponentById(ResourceTable.Id_layout_next);
                            //创建Tetris组件，用来显示下一个方块，drawBlock不为空
                            Tetris nextTetris = new Tetris(MainAbility.this, layoutNext, tetris.nextBlock);
                            nextTetris.mode_flag=game_mode;
                        }
                    });
                }
            });
            //消除行的监听事件

            tetris.setOnTetrisRowMovedListener(new TetrisRowRemovedListener() {
                @Override
                public void rowRmoved(int rowCount) {
                    Text textScore = (Text) findComponentById(ResourceTable.Id_score);
                    //获取当前积分
                    currentScore[0] = Integer.parseInt(textScore.getText());
                    //积分累加
                    currentScore[0] += fibonacci(rowCount) * 10;
                    //跟新积分
                    textScore.setText(String.valueOf(currentScore[0]));
                }
            });


            //游戏结束监听事件
            tetris.setOnTetrisGameOverListener(new TetrisGameoverListener() {
                @Override
                public void onGameOver() {
                    MyToastdialog.showTip(getContext(), "游戏结束");
                    isOver = true;
                    timer_seconds.stop();
//                    timer_seconds.cancel();
//                    Tools.showTip(MainAbility.this,"本局时长"+seconds+"秒"+" "+currentScore[0]+"分");
                    //获取当前时间
                    Date date = new Date();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");

                    //数据插入数据库
                    ValuesBucket bucket = new ValuesBucket();
                    bucket.putString("date", dateFormat.format(date));
                    bucket.putInteger("score", currentScore[0]);
                    bucket.putString("seconds", timer_seconds.getText());
                    try {
                        if(Objects.equals(game_mode, "classic")){
                            int rowNum = helper.insert(uri, bucket);
                        }else if(Objects.equals(game_mode, "difficulty")){
                            int rowNum = helper.insert(uri_df, bucket);
                        }
                    } catch (Exception e) {
                    }


                }
            });

            //水平左移
            Button buttonMoveLeft = (Button) findComponentById(ResourceTable.Id_move_left);
            if (buttonMoveLeft != null) {
                buttonMoveLeft.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        tetris.moveLeft();
                    }
                });
            }
            //水平右移
            Button buttonMoveRight = (Button) findComponentById(ResourceTable.Id_move_right);
            if (buttonMoveRight != null) {
                buttonMoveRight.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        tetris.moveRight();
                    }
                });
            }

            //快速下落
            Button buttonMoveQuickly = (Button) findComponentById(ResourceTable.Id_move_quickly);
            if (buttonMoveQuickly != null) {
                buttonMoveQuickly.setTouchEventListener(new Component.TouchEventListener() {
                    @Override
                    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                        if (tetris.isPlaying) {
                            if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
                                //按下时快速下落
                                tetris.moveQuickly();
                            } else if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP) {
                                //抬起时恢复正常速度
                                tetris.moveNormally();
                            }
                        }
                        return true;
                    }
                });
            }

        }

        //重新开始
        Button button_back_home = (Button) findComponentById(ResourceTable.Id_button_back_home);
        if (button_back_home != null) {
            button_back_home.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (isStart && !isOver) {

                        DirectionalLayout dl = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                                .parse(ResourceTable.Layout_cmddialog_restart, null, false);

                        MyCommondialog commondialog = new MyCommondialog(getContext(), dl);

                        Text title = (Text) dl.findComponentById(ResourceTable.Id_title);
                        Button submit = (Button) dl.findComponentById(ResourceTable.Id_submit);
                        Button cancel = (Button) dl.findComponentById(ResourceTable.Id_cancel);

                        submit.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                terminateAbility();
                            }
                        });
                        //取消事件
                        cancel.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                commondialog.destroy();
                            }
                        });

                    } else {
                        terminateAbility();
                    }
                }
            });
        }
    }
//斐波那契数列，奖励分机制
    public int fibonacci(int n) {
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

}


